package com.zoweunion.mechanic.service.base.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoweunion.mechanic.dao.base.EnclosureDao;
import com.zoweunion.mechanic.service.base.EnclosureService;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.Page;
import com.zoweunion.mechanic.util.UuidUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description:
 * @author: skyxu
 * @date: 2019/2/11 0011 14:12
 * @Copyright: 2019 www.zoweunion.com Inc. All rights reserved.
 */
@Service
@Transactional
public class EnclosureServiceImpl implements EnclosureService {

    @Autowired
    private EnclosureDao enclosureDao;

    @Override
    public int addEnclosure(Map<String, Object> reqMap) throws MyException {
        String id = "";
        //新增需要将车辆绑定的所有电子围栏信息删掉
        if(reqMap.get("carId") != null && reqMap.get("carId") != ""){
            String carId = reqMap.get("carId").toString();
            List<String> enclosureIdList = this.enclosureDao.getEnclosureIdListByCarId(carId);
            Map<String, Object> parMap = new HashMap<>();
            enclosureIdList.forEach(item->{
                parMap.put("id", item);
                try {
                    delEnclosureList(parMap);
                } catch (MyException e) {
                    e.printStackTrace();
                }
            });
        }
        if (reqMap.get("id") != null && reqMap.get("id") != "") {
            delEnclosureList(reqMap);
            id = reqMap.get("id").toString();
        } else {
            id = UuidUtil.get32UUID();
            reqMap.put("id", id);
        }
        int addResult = this.enclosureDao.addEnclosure(reqMap);
        if (reqMap.get("car") != null && StringUtils.isNotBlank(reqMap.get("car").toString())) {
            //取电子围栏绑定的车辆
            String car = reqMap.get("car").toString();
            JSONArray enclosureCars = JSONObject.parseArray(car);
            List<Map<String, Object>> carMaps = new ArrayList<>();
            for (int i = 0; i < enclosureCars.size(); i++) {
                Map<String, Object> map = new HashMap<>(16);
                JSONObject enclosureCar = enclosureCars.getJSONObject(i);
                String c_id = enclosureCar.getString("c_id");
                String things_id = enclosureCar.getString("things_id");
                String opc_path = enclosureCar.getString("opc_path");
                map.put("id", UuidUtil.get32UUID());
                map.put("e_id", id);
                map.put("c_id", c_id);
                map.put("things_id", things_id);
                map.put("opc_path", opc_path);
                carMaps.add(map);
            }
            int result = this.enclosureDao.addEnclosureCar(carMaps);
        }
        if (reqMap.get("user") != null && StringUtils.isNotBlank(reqMap.get("user").toString())) {
            //取电子围栏绑定的通知人
            String user = reqMap.get("user").toString();
            JSONArray enclosureUsers = JSONObject.parseArray(user);
            List<Map<String, Object>> userMaps = new ArrayList<>();
            for (int i = 0; i < enclosureUsers.size(); i++) {
                Map<String, Object> map = new HashMap<>(16);
                JSONObject enclosureUser = enclosureUsers.getJSONObject(i);
                String user_id = enclosureUser.getString("user_id");
                String user_name = enclosureUser.getString("user_name");
                map.put("id", UuidUtil.get32UUID());
                map.put("e_id", id);
                map.put("user_id", user_id);
                map.put("user_name", user_name);
                userMaps.add(map);
            }
            int result = this.enclosureDao.addEnclosureNotifier(userMaps);
        }
        if (!"1".equals(reqMap.get("type").toString())) {
            //type为2 电子围栏是多边形  保存多边形
            JSONArray lonLats = JSONArray.parseArray(reqMap.get("lon_lat").toString());
            List<Map<String, Object>> maps = new ArrayList<>();
            for (int i = 0; i < lonLats.size(); i++) {
                Map<String, Object> map = new HashMap<>(16);
                JSONArray lonLat = lonLats.getJSONArray(i);
                if (lonLat.size() >= 3) {
                    String lon = ((BigDecimal) lonLat.get(0)).toString();
                    String lat = ((BigDecimal) lonLat.get(1)).toString();
                    Integer number = Integer.valueOf(lonLat.get(2).toString());
                    map.put("id", UuidUtil.get32UUID());
                    map.put("lng", lon);
                    map.put("lat", lat);
                    map.put("e_id", id);
                    map.put("number", number);
                    maps.add(map);
                }
            }
            int result = 0;
            if (maps.size() > 0) {
                result = this.enclosureDao.addEnclosurePolygon(maps);
            }
            if (result <= 0) {
                throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");
            }
        }
        return addResult;
    }

    @Override
    public Map<String, Object> getEnclosureList(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        List<Map<String, Object>> enclosure = this.enclosureDao.getEnclosureList(reqMap);
        if (enclosure.size() > 0) {
            //获取电子围栏绑定的车辆
            List<Map<String, Object>> enclosureCars = enclosureDao.getAllEnclosureCarByEId(enclosure);
            for (Map<String, Object> enclosureMap : enclosure) {
                List<Map<String, Object>> cars = new ArrayList<>();
                for (Map<String, Object> enclosureCarMap : enclosureCars) {
                    if (enclosureMap.get("id").toString().equals(enclosureCarMap.get("e_id").toString())) {
                        cars.add(enclosureCarMap);
                    }
                }
                enclosureMap.put("car", cars);
            }
            //如果是多边形 获取电子围栏经纬度
            List<Map<String, Object>> enclosurePolygons = enclosureDao.getAllEnclosurePolygonByEId(enclosure);
            for (Map<String, Object> enclosureMap : enclosure) {
                List<Map<String, Object>> polygons = new ArrayList<>();
                for (Map<String, Object> enclosurePolygonMap : enclosurePolygons) {
                    if (enclosureMap.get("id").toString().equals(enclosurePolygonMap.get("e_id").toString())) {
                        polygons.add(enclosurePolygonMap);
                    }
                }
                if (polygons.size() > 0) {
                    Collections.sort(polygons, new Comparator<Map<String, Object>>() {
                        @Override
                        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                            return (Integer) o1.get("number") > (Integer) o2.get("number") ? 1 : (((Integer) o1.get("number")).equals((Integer) o2.get("number")) ? 0 : -1);
                        }
                    });
                    Object[] polygonArray = new Object[polygons.size()];
                    for (int i = 0; i < polygons.size(); i++) {
                        Map<String, Object> polygonMap = polygons.get(i);
                        List<BigDecimal> list = new ArrayList<>();
                        BigDecimal lat = new BigDecimal(polygonMap.get("lat").toString());
                        BigDecimal lng = new BigDecimal(polygonMap.get("lng").toString());
                        BigDecimal number = new BigDecimal(polygonMap.get("number").toString());
                        list.add(lng);
                        list.add(lat);
                        list.add(number);
                        Object[] array = list.toArray();
                        polygonArray[i] = array;
                    }
                    enclosureMap.put("polygon", polygonArray);
                }
            }
        }
        Integer count = this.enclosureDao.getEnclosureListCount(reqMap);
        Map<String, Object> map = new HashMap<>(16);
        map.put("enclosure", enclosure);
        map.put("count", count);
        return map;
    }

    @Override
    public Map<String, Object> getEnclosureInfo(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> map = new HashMap<>(16);
        //获取电子围栏主表
        Map<String, Object> enclosure = this.enclosureDao.getEnclosureById(reqMap);
        //获取电子围栏绑定的车辆
        List<Map<String, Object>> enclosureCars = this.enclosureDao.getEnclosureCarByEId(reqMap);
        //获取电子围栏绑定的通知人
        List<Map<String, Object>> enclosureNotifiers = this.enclosureDao.getEnclosureNotifierByEId(reqMap);
        if (!"1".equals(enclosure.get("type").toString())) {
            //如果是多边形 获取电子围栏经纬度
            List<Map<String, Object>> enclosurePolygons = this.enclosureDao.getEnclosurePolygonByEId(reqMap);
            Collections.sort(enclosurePolygons, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return (Integer) o1.get("number") > (Integer) o2.get("number") ? 1 : (((Integer) o1.get("number")).equals((Integer) o2.get("number")) ? 0 : -1);
                }
            });
            Object[] polygonArray = new Object[enclosurePolygons.size()];
            for (int i = 0; i < enclosurePolygons.size(); i++) {
                Map<String, Object> polygonMap = enclosurePolygons.get(i);
                List<BigDecimal> list = new ArrayList<>();
                BigDecimal lng = new BigDecimal(polygonMap.get("lng").toString());
                BigDecimal lat = new BigDecimal(polygonMap.get("lat").toString());
                BigDecimal number = new BigDecimal(polygonMap.get("number").toString());
                list.add(lng);
                list.add(lat);
                list.add(number);
                Object[] array = list.toArray();
                polygonArray[i] = array;
            }
            map.put("enclosurePolygons", polygonArray);
        }
        map.put("enclosureCars", enclosureCars);
        map.put("enclosureNotifiers", enclosureNotifiers);
        map.put("enclosure", enclosure);
        return map;
    }

    @Override
    public int delEnclosureList(Map<String, Object> reqMap) throws MyException {
        int result = this.enclosureDao.delEnclosureList(reqMap);
        int resultCar = this.enclosureDao.delEnclosureCar(reqMap);
        int resultPolygon = this.enclosureDao.delEnclosurePolygon(reqMap);
        int resultNotifier = this.enclosureDao.delEnclosureNotifier(reqMap);
        return result;
    }

    @Override
    public Map<String, Object> getServerAllUser(Map<String, Object> reqMap) throws MyException {
        List<Map<String, Object>> users = new ArrayList<>();
        users = enclosureDao.getServerAllUser(reqMap);
        Map<String, Object> map = new HashMap<>(2);
        map.put("user", users);
        return map;
    }
}
